package MyThread;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-10-16
 * Time: 10:33
 */
public class Demo2 {
    /**优化内存可见性:
     *
     * 方案一：
     */


    private volatile static int flag = 0;

        public static void main1(String[] args) {
            Thread t1 = new Thread(()->{

                while (flag == 0){

                }
            });

            Thread t2 = new Thread(()->{
                Scanner in = new Scanner(System.in);
                System.out.println("请输入 flag");
                flag = in.nextInt();
            });

            t1.start();
            t2.start();
        }



    /**优化内存可见性:
     *
     * 方案二：(常用)
     */
    public static void main(String[] args) {
        Thread t1 = new Thread(()->{

            while (flag == 0){
                try {
                    /** 本来，这个循环会执行几千万上亿次然后被优化，
                     * 但是加了sleep,循环次数发幅度降，sleep占用了比load 读内存 flag更长的时间，此时又不优化flag无足轻重，编译器就放弃优化了
                     *
                     */
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread t2 = new Thread(()->{
            Scanner in = new Scanner(System.in);
            System.out.println("请输入 flag");
            flag = in.nextInt();
        });

        t1.start();
        t2.start();
    }
}
